package club.itstudio.itouc.controller.jw.course

import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.entity.Campus
import club.itstudio.itouc.entity.CourseType
import club.itstudio.itouc.util.Mysql
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController



@RestController
class Public (val mysql: Mysql,
              val redis: Redis){
    /**
     * 获取公共课，公共课与教务系统的公共基础课不同
     * 公共课包括公共基础课和通识课，并且细分为普通公共课、通识课，通识Mooc、体育课、高级英语、思政军事表
     * @param campus: 校区： All, 崂山校区、鱼山校区
     * @param type: 课程类型: All, Public,PE, Polity,AdvancedEnglish,Common,CommonMooc
     */
    @GetMapping("/jw/course/public/{campus}/{type}")
    fun publicCourse(@PathVariable campus: Campus,
                     @PathVariable type: CourseType,
                     @RequestParam keyword: String): Result<Any> {
        val publicCourse = mysql.getPublicCourse(campus.campus, type.name, keyword)
        // 格式化为 课程名-校区-类型
        val courseMap = mutableMapOf<String, PublicCourseData>()
        publicCourse.forEach {
            if (courseMap.containsKey(it["className"])) {
                val course = courseMap[it["className"]]
                course?.campus?.add(it.getOrDefault("campus", ""))
                if (course?.type == "Public" || course?.type == "Common") {
                    course.type = it.getOrDefault("type", "")
                }
            } else {
                val courseData = PublicCourseData(mutableSetOf(it.getOrDefault("campus", "")), it.getOrDefault("type", ""))
                courseMap[it.getOrDefault("className", "")] = courseData
            }
        }
        val courseList = mutableListOf<Map<String, String>>()
        courseMap.forEach{courseList.add(mapOf(
                    "className" to it.key,
                    "campus" to it.value.campus(),
                    "type" to it.value.type
        ))}
        return ResultUtil.success(courseList)
    }

    /**
     * 根据课程名获取公共课列表
     */
    @GetMapping("/jw/course/public/elective/{className}")
    fun getPublicClassByName(@PathVariable className: String): Result<Any> {
        val classNums = mysql.getPublicCourseByName(className)
        val data = redis.getCourseList(classNums)
        return ResultUtil.success(data)
    }

}

data class PublicCourseData(
        val campus: MutableSet<String>,
        var type: String){
    fun campus(): String{
        return if (campus.size == 1) campus.first().substring(0, 2)
        else "${campus.first().substring(0, 2)}/${campus.last().substring(0, 2)}"
    }
}

